import { friendData, PullTypeEnum, ApprovingEnum, FRIEND_TYPE } from "../util/friendData";
import { GCtrl } from "../util/GCtrl";

export class NewFriendData {
    private constructor() {
        this.onEvent();
        // this.getAllNewFriendData();
    };
    private static m_pInstance: NewFriendData = null;
    public static getInstance() {
        if (!this.m_pInstance) {
            this.m_pInstance = new NewFriendData();
        }
        return this.m_pInstance;
    }
    //--------------
    //member
    //--------------

    //private-------
    private friendDataArr: any = {};
    private arrList: any = {};
    private reqList: any = {};
    private isCheckedList: any = {};
    private newFriendNum: number = 0;
    private verifyNum: number = 0;

    //public--------


    //--------------
    //function
    //--------------

    //--------------
    private onEvent() {
        GCtrl.eventIndex['ServerNtc_NewFriendData'] = cc.vv.eventCustom.on("ServerNtc", this.serverNtc.bind(this));
        GCtrl.eventIndex['deleteFriendSuccess_nfd'] = cc.vv.eventCustom.on('deleteFriendSuccess', this.deleteFriendSuccess.bind(this), this);
        GCtrl.eventIndex['logout_nfd'] = cc.vv.eventCustom.on('logout', this.logout.bind(this), this);
    }
    private offEvent() {
        GCtrl.eventIndex['deleteFriendSuccess_nfd'] && (cc.vv.eventCustom.off('deleteFriendSuccess', GCtrl.eventIndex['deleteFriendSuccess_nfd']), delete GCtrl.eventIndex['deleteFriendSuccess_nfd']);
        GCtrl.eventIndex['logout_nfd'] && (cc.vv.eventCustom.off('logout', GCtrl.eventIndex['logout_nfd']), delete GCtrl.eventIndex['logout_nfd']);
        GCtrl.eventIndex['ServerNtc_NewFriendData'] && cc.vv.eventCustom.off("ServerNtc", GCtrl.eventIndex['ServerNtc_NewFriendData']);
        delete GCtrl.eventIndex['ServerNtc_NewFriendData'];
    }
    private getAllNewFriendData() {
        this.resetMembers();
        if (!GCtrl.dataConfig.SelfData) return;
        let req_arr = GCtrl.dataConfig.SelfData.request;
        if (!req_arr || !req_arr.length) return;
        let reqArr: any[] = [];
        for (let i in req_arr) {
            let req = req_arr[i];
            reqArr.push({
                type: PullTypeEnum.RID,
                user_id: req.request_id
            });
            this.arrList[req.request_id] = req;
        }
        this.requestData('PullUsersInfo', { req: reqArr }, this.saveData.bind(this));
    }
    private serverNtc(data: any) {
        if (!data) return;
        if (!data.length) return;
        else {
            let ntc = data[0];
            let fri_req_arr = ntc.fri_req;
            if (fri_req_arr && fri_req_arr.length) {
                let reqArr: any[] = [];
                for (let i in fri_req_arr) {
                    let req = fri_req_arr[i];
                    reqArr.push({
                        type: PullTypeEnum.RID,
                        user_id: req.request_id
                    });
                    this.reqList[req.request_id] = req;
                }
                this.requestData('PullUsersInfo', { req: reqArr }, this.updateNewFriendData.bind(this));
            }
        }
    }
    private resetMembers() {
        this.friendDataArr = {};
        this.arrList = {};
        this.reqList = {};
        this.isCheckedList = {};
        this.newFriendNum = 0;
    }
    private logout() {
        NewFriendData.m_pInstance = null;
        this.resetMembers();
        this.offEvent();
    }

    private requestData(msgType: string, msg: any, callback = null, ...args) {
        cc.vv.GLUtils.sendRequest(msgType, msg, function (error, data) {
            if (data.errorcode) {
                cc.vv.GLUtils.showTips(data.errordes);
            } else {
                callback && callback(data, ...args);
            }
        }.bind(this));
    }
    private saveData(data: any) {
        if (!data || !data.res) return false;
        let res = data.res;
        let timestamp: number = 0;
        let status: number = 0;
        let comments: string = "";
        for (let j in res) {
            let usersInfo = res[j];
            for (let i in usersInfo.user_info) {
                let userData: any = friendData.s2cData(usersInfo.user_info[i]);
                let reqInfo = this.arrList[userData.Id];
                if (!reqInfo) continue;
                timestamp = reqInfo.timestamp;
                status = reqInfo.status;
                comments = reqInfo.comments;
                if (status == ApprovingEnum.DELETE) continue;
                userData.sendMsgTime = GCtrl.GMT2Date(timestamp);
                userData.reqComments = comments;
                userData.status = status;
                userData.timestamp = timestamp;
                this.friendDataArr[userData.Id] = userData;
                this.setVerifyNum(this.verifyNum + 1);
                (status == ApprovingEnum.INIT || status == ApprovingEnum.READ) ?
                    (this.setNewFriendNum(this.newFriendNum + 1), this.isCheckedList[userData.Id] = false) :
                    this.isCheckedList[userData.Id] = true;
                delete this.arrList[userData.Id];
            }
        }
        return true;
    }
    private updateNewFriendData(userData: any) {
        if (!userData || !userData.res) return false;
        let res = userData.res;
        for (let i in res) {
            let usersInfo = res[i];
            let reqInfo = this.reqList[usersInfo.user_info[0].rid];
            if (!reqInfo) continue;
            let status = reqInfo.status;
            switch (status) {
                case ApprovingEnum.INIT: //{ this.updateNewFriendDataInit(userData, status, comments); } break;
                case ApprovingEnum.READ: { this.updateNewFriendDataRead(usersInfo); } break;
                case ApprovingEnum.AGREE: { this.updateNewFriendDataAgree(usersInfo); } break;
                case ApprovingEnum.REJECT: { this.updateNewFriendDataRefuse(usersInfo); } break;
                case ApprovingEnum.DELETE: { this.updateNewFriendDataDelete(usersInfo); } break;
            }
        }
        return true;
    }
    private updateNewFriendDataInit(userData: any) {

    }
    private updateNewFriendDataRead(userData: any) {
        if (!userData) return false;
        if (!this.friendDataArr) this.friendDataArr = {};
        for (let i in userData.user_info) {
            userData = friendData.s2cData(userData.user_info[i]);
            let reqInfo = this.reqList[userData.Id];
            if (!reqInfo) continue;
            let timestamp = reqInfo.timestamp;
            let status = reqInfo.status;
            let comments = reqInfo.comments;
            let time = GCtrl.turnLocalDateToMyDate(new Date().toDateString());
            let userInfo = this.friendDataArr[userData.Id];
            if (!userInfo) {
                userData.sendMsgTime = time;
                userData.reqComments = comments;
                userData.status = status;
                userData.timestamp = timestamp;
                this.friendDataArr[userData.Id] = userData;
                this.isCheckedList[userData.Id] = false;
                this.setVerifyNum(this.verifyNum + 1);
                this.setNewFriendNum(this.newFriendNum + 1);
                cc.vv.eventCustom.emit('updateNewReqNum');
            }
            //已有请求数据
            else {
                //若已读就重置状态
                this.isCheckedList[userInfo.Id] == true && (this.setNewFriendNum(this.newFriendNum + 1), cc.vv.eventCustom.emit('updateNewReqNum'));
                this.isCheckedList[userInfo.Id] = false;
                this.friendDataArr[userData.Id].status = ApprovingEnum.INIT;
                this.friendDataArr[userData.Id].reqComments = comments;
                this.friendDataArr[userData.Id].sendMsgTime = time;
                this.friendDataArr[userData.Id].timestamp = timestamp;
            }
            cc.vv.eventCustom.emit('addNewFriendSuccess', this.friendDataArr[userData.Id]);
            delete this.reqList[userData.Id];
        }
        return true;
    }
    private updateNewFriendDataAgree(userData: any) {
        if (!userData) return false;
        if (!this.friendDataArr) return false;
        let userInfo = this.friendDataArr[userData.Id];
        if (!userInfo) return false;
        let reqInfo = this.reqList[userData.Id];
        if (!reqInfo) return false;
        status = reqInfo.status;
        // let comments = reqInfo.comments;
        //更新状态
        this.friendDataArr[userData.Id].friendType = FRIEND_TYPE.Friend;
        this.friendDataArr[userData.Id].status = status;
        cc.vv.eventCustom.emit('agreeUserSuccess', this.friendDataArr[userData.Id]);
        return true;
    }
    private updateNewFriendDataRefuse(userData: any) {
        if (!userData) return false;
        if (!this.friendDataArr) return false;
        let userInfo = this.friendDataArr[userData.Id];
        if (!userInfo) return false;
        //更新状态
        this.friendDataArr[userData.Id].friendType = FRIEND_TYPE.notFriend;
        this.friendDataArr[userData.Id].status = status;
        cc.vv.eventCustom.emit('refuseUserSuccess', this.friendDataArr[userData.Id]);
    }
    private updateNewFriendDataDelete(userData: any) {
        if (!userData) return false;
        if (!this.friendDataArr) return false;
        let userInfo = this.friendDataArr[userData.Id];
        if (!userInfo) return false;
        //删除数据
        delete this.friendDataArr[userData.Id];
        cc.vv.eventCustom.emit('deleteUserSuccess', this.friendDataArr[userData.Id]);
        return true;
    }
    private deleteFriendSuccess(data) {
        let userId = data[0];
        let userData: friendData = this.friendDataArr[userId];
        if (!userData) return false;
        userData.friendType = FRIEND_TYPE.notFriend;
        return true;
    }

    //--------------
    init() {
        this.getAllNewFriendData();
    }
    /**
     * 获取所有加好友请求消息数据
     * @param eventName 获取数据的事件名
     */
    public getData(eventName: string = '') {
        cc.vv.eventCustom.emit(eventName, this.friendDataArr);
        return this.friendDataArr;
    }
    /**
     * 筛选符合条件的数据
     * @param condition 筛选条件
     */
    public shaiXuanData(condition: string = '') {
        if (condition == '') return this.friendDataArr;
        let _hArr = {};
        let { ...tempArr } = this.friendDataArr;
        for (let i in tempArr) {
            let friendData = tempArr[i];
            let name = friendData.name;
            if (name.indexOf(condition) == -1) {
            }
            else {
                _hArr[i] = friendData;
            }
        }
        return _hArr;
    }
    /**
     * 同意好友请求
     * @param Id 好友ID
     */
    public agreeRequest(Id: number) {
        let userData: any = this.friendDataArr[Id];
        if (!userData) return false;
        userData.friendType = FRIEND_TYPE.Friend;
        userData.status = ApprovingEnum.AGREE;
        cc.vv.eventCustom.emit('agreeUserSuccess', Id);
        // return true;
    }
    /**
     * 拒绝好友请求
     * @param Id 用户ID
     */
    public refuseRequest(Id: number) {
        let userData: any = this.friendDataArr[Id];
        if (!userData) return false;
        userData.friendType = FRIEND_TYPE.notFriend;
        userData.status = ApprovingEnum.REJECT;
        cc.vv.eventCustom.emit('refuseUserSuccess', Id);
        return true;
    }
    /**
     * 查看请求
     * @param Id 被查看用户ID
     */
    public checkRequest(Id: number) {
        if (this.isCheckedList[Id]) return false;
        this.isCheckedList[Id] = true;
        this.newFriendNum > 0 && this.setNewFriendNum(this.newFriendNum - 1);
        return true;
    }
    /**
     * 用户是否被查看
     * @param Id 用户ID
     */
    public isChecked(Id: number) {
        return !!this.isCheckedList[Id];
    }
    /**
     * 获取用户请求当前状态
     * @param Id 用户ID
     */
    public getRequestStatus(Id: number): number {
        let reqData = this.friendDataArr[Id];
        if (!reqData) return -1;
        return reqData.status;
    }
    /**
     * 获取当前新请求条数
     */
    public getNewFriendNum() {
        return this.newFriendNum;
    }
    /**
     * 设置新请求条数
     * @param num 数量
     */
    public setNewFriendNum(num: number) {
        if (num == null || num == void 0) return false;
        this.newFriendNum = num;
        cc.vv.eventCustom.emit('updateNewReqNum');
        return true;
    }
    /**
     * 移除新好友请求
     * @param Id 用户ID
     */
    public RemoveReqData(Id: number) {
        let userData: any = this.friendDataArr[Id];
        if (!userData) return false;
        this.newFriendNum > 0 && !this.isChecked(Id) && this.setNewFriendNum(this.newFriendNum - 1);
        userData.status = ApprovingEnum.DELETE;
        delete this.friendDataArr[Id];
        delete this.isCheckedList[Id];
        this.setVerifyNum(this.verifyNum - 1);
        this.requestData('ApprovingFriend', { user_id: userData.Id, approving: ApprovingEnum.DELETE });
        cc.vv.eventCustom.emit('removeReqDataSuccess', Id);
        return true;
    }
    public setVerifyNum(num: number) {
        if (num == void 0) return false;
        num < 0 && (num = 0);
        this.verifyNum = num;
        return true;
    }
    public getVerifyNum() {
        return this.verifyNum;
    }
}